import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		userInfo: null,
		isLogin: false,
		openid: null,
		current: 0
	},
	mutations: {
		SET_USER_INFO(state, payload) {
			state.userInfo = payload.userInfo;
			state.openid = payload.openid;
			state.isLogin = true;
			uni.setStorageSync('user_token',payload.user_token);
		},
		CLEAR_USER_INFO(state) {
			state.userInfo = null;
			state.openid = null;
			state.isLogin = false;
			uni.removeStorageSync('user_token');			
		},
		SET_TABBAR_INDEX(state, payload) {
			console.log('payload',payload);
			state.current = payload.current
		}
	},
	actions: {
		async login({ commit }) {
			try {
				uni.getUserProfile({
					desc: '用于完善用户资料', // 必填项
					success: async (res) => {
						//console.log('用户信息:', res.userInfo);
						const loginRes = await uni.login({
							provider: 'weixin'
						});
						//console.log('ssssss',loginRes);
						// 调用云函数，将code和用户信息传给云函数
						const cloudRes = await uniCloud.callFunction({
							name: 'wechatAuth',
							data: {
								code: loginRes.code,
								userInfo: res.userInfo
							}
						});
						
						//console.log('云函数返回:', cloudRes);
						//uni.setStorageSync('user_token',{"openid": cloudRes.result.data.openid,"expire_time": cloudRes.result.data.expire_time})
						
						// 提交到 vuex
						commit('SET_USER_INFO', {
						  userInfo: res.userInfo,
						  openid: cloudRes.result.data.openid,
						  user_token: {"openid": cloudRes.result.data.openid,"expire_time": cloudRes.result.data.expire_time}
						});
						uni.showToast({ title: '登录成功' });
						return true;
					},
					fail: (err) => {
						console.error('获取失败:', err);
						uni.showToast({ title: '登录失败' });					
						return false;
					}
				});
				
			} catch (err) {
				uni.showToast({
					title: '出错了',
					icon: 'none'
				});
				console.error(err);
				return false;
			}
		},
		logout({ commit }) {
			uni.showToast({
				title: '已退出登录'
			});
			commit('CLEAR_USER_INFO');
		},
		// 校验当前会话时间是否过期
		async restoreLoginState({ commit }) {
			const cached = await uni.getStorageSync('user_token');
			console.log('cached', cached);
			if (cached && cached.expire_time > Date.now() && cached.openid !== null) {
				const cloudRes = await uniCloud.callFunction({
					name: 'getCurrentUserInfo',
					data: {
						openid: cached.openid
					}
				});
				console.log('cloudres', cloudRes);
				if (cloudRes.result && cloudRes.result.data && cloudRes.result.data.length > 0) {
					commit('SET_USER_INFO', {
						openid: cached.openid,
						userInfo: cloudRes.result.data[0],
						user_token: {"openid": cached.openid, "expire_time": Date.now() + 3 * 24 * 60 * 60 * 1000}
					});
					// uni.setStorageSync('user_token',
					// {"openid": cached.openid,
					// "expire_time": Date.now() + 3 * 24 * 60 * 60 * 1000})
					console.log("重新刷新token");
					return true;
				}else{
					commit('CLEAR_USER_INFO');
					uni.showToast({
						title: '请重新登录'
					});
					return false;
				}
				
			}else{
				commit('CLEAR_USER_INFO');
				uni.showToast({
					icon: "error",
					title: '请重新登录'
				});
				console.log("过期了");
				return false;
			}

		}
	},
	getters: {
		getUserInfo: state => state.userInfo,
		getIsLogin: state => state.isLogin,
		getOpenId: state => state.openid,
		getCurrent: state => state.current
	}
});